package com.birdboot.http;

import org.omg.CORBA.PRIVATE_MEMBER;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class HttpServletResponse {
    private Socket socket;
    private int statusCode = 200;//状态代码
    private String statusReason = "OK";

    //响应正文相关信息
    private File contentFile;

    public HttpServletResponse(Socket socket) {
        this.socket = socket;
    }

    //发送状态行
    private void sendStatusLine() throws IOException {
        println("HTTP/1.1" + " " + statusCode + " " + statusReason);
    }

    //发送响应头
    private void sendHeader() throws IOException {
        println("Content-Type: text/html");
        println("Content-Length: " + contentFile.length());
        //单独发送回车+换行表达响应头发完了
        println("");
    }

    //发送响应正文
    private void sendContent() throws IOException {
        OutputStream out = socket.getOutputStream();
        FileInputStream fis = new FileInputStream(contentFile);
        byte[] data = new byte[1024 * 10];
        int len;
        while ((len = fis.read(data)) != -1) {
            out.write(data, 0, len);
        }
    }

    /*V8新增,这个方法就是元ClientHandler第三步发送响应的代码*/
    public void response() throws IOException {
        //3发送响应
        //3.1发送状态行
        sendStatusLine();
        //3.2发送响应头
        sendHeader();
        //3发送响应正文
        sendContent();

    }

    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        out.write(line.getBytes(StandardCharsets.ISO_8859_1));
        out.write(13);//单独发送回车符
        out.write(10);//单独发送换行符
    }

    //为属性添加get,set方法

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public File getContentFile() {
        return contentFile;
    }

    public void setContentFile(File contentFile) {
        this.contentFile = contentFile;
    }
}
